from Controller.BaseController import BaseController
from Common.DuplicatedInstanceError import DuplicatedInstanceError
from Common.User import User
from Common.GroupOrg import Group
from Utility import FormData
from Utility import UserRole
from Utility import ViewName
from Utility import IsEmptyString
from Utility import TemplateValueName

class CreateUserController(BaseController):
    """
    Let company admin create user and assign user to a group
    """
    def get(self):
        u = self.GetCurrentUser()
        
        # must be company admin
        if not self.VerifyCurrentUserRole(u, UserRole.CompanyAdmin, "/create/user"):
            return
        # make sure current user is admin account
        # list all groups which belong the company which is associated with current user
        c = u.Ref_Company
        template_values = {'Groups': c.Groups, "CompanyName": c.CompanyName, "CompanyKey":c.key()}
        self.Render(ViewName.D_CREATEUSER, template_values)
    
    
    def post(self):
        u = self.GetCurrentUser()
        
        # must be company admin
        if not self.VerifyCurrentUserRole(u, UserRole.CompanyAdmin, "/create/user"):
            return
        
        userName = self.request.get(FormData.USER_NAME)
        password = self.request.get(FormData.PASSWORD)
        email = self.request.get(FormData.EMAIL)
        groupKey = self.request.get(FormData.GROUP_KEY)
        if IsEmptyString(groupKey):
            pass # return wrong
        g = Group.get(groupKey)

        c = u.Ref_Company        
        template_values = {'Groups': c.Groups, "CompanyName": c.CompanyName, "CompanyKey":c.key()}
        
        try:
            u = User(parent=g.Ref_Company,
                     key_name=userName,
                     UserName=userName,
                     Password=password,
                     DisplayName=userName,
                     Email=email,
                     Role=UserRole.User,
                     Ref_Company=g.Ref_Company,
                     Ref_Group=g)
            u.TransactionPut()
            template_values[TemplateValueName.SUCCESS_MESSAGE] = "New user, " + userName + ", was created successfully!"
        except DuplicatedInstanceError:
            template_values[TemplateValueName.ERROR_MESSAGE] = "User, " + userName + ", already exists!"

        self.Render(ViewName.D_CREATEUSER, template_values)
        
 
        
"""
            self.response.out.write("<br />")
            self.response.out.write(User.gql ('WHERE UserName = :1', userName).get().key())
            
                    self.response.out.write("<br />")
        self.response.out.write(db.Key.from_path("User", userName, parent=g.Ref_Company.key()))    
"""
